package ds_industry_2025.ds.ds_06.T2

import org.apache.hudi.DataSourceWriteOptions.{PARTITIONPATH_FIELD, PRECOMBINE_FIELD, RECORDKEY_FIELD}
import org.apache.hudi.QuickstartUtils.getQuickstartWriteConfigs
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions._

import java.text.SimpleDateFormat
import java.util.Calendar

/*
    6、将ods_ds_hudi库中order_detail表昨天的分区（子任务一中生成的分区）数据抽取到dwd_ds_hudi库中fact_order_detail的动态分
    区表，分区字段为etl_date，类型为String，取create_time值并将格式转换为yyyyMMdd，并添加dwd_insert_user、dwd_insert_time、
    dwd_modify_user、dwd_modify_time四列，其中dwd_insert_user、dwd_modify_user均填写“user1”，dwd_insert_time、
    dwd_modify_time均填写当前操作时间，并进行数据类型转换。id作为primaryKey，dwd_modify_time作为preCombineField。使用
    spark-shell执行show partitions dwd_ds_hudi.fact_order_detail命令，将结果截图粘贴至客户端桌面【Release\任务B提交结
    果.docx】中对应的任务序号下。
 */
object t6 {
  def main(args: Array[String]): Unit = {
    val spark = SparkSession.builder()
      .master("local[*]")
      .appName("t6")
      .config("hive.exec.dynamic.partition.mode","nonstrict")
      .config("spark.serializer","org.apache.spark.serializer.KryoSerializer")
      .config("spark.sql.extensions","org.apache.spark.sql.hudi.HoodieSparkSessionExtension")
      .enableHiveSupport()
      .getOrCreate()

    val day=Calendar.getInstance()
    val current_time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(day.getTime)
    day.add(Calendar.DATE,-1)
    val yesterday=new SimpleDateFormat("yyyyMMdd").format(day.getTime)

    val ods_path="hdfs://192.168.40.110:9000/user/hive/warehouse/ods_ds_hudi.db/order_detail"
    val dwd_path="hdfs://192.168.40.110:9000/user/hive/warehouse/dwd_ds_hudi.db/fact_order_detail"

    spark.read.format("hudi").load(ods_path)
      .where(col("etl_date")===lit(yesterday))
      .withColumn("dwd_insert_user", lit("user1"))
      .withColumn("dwd_insert_time", to_timestamp(lit(current_time)))
      .withColumn("dwd_modify_user", lit("user1"))
      .withColumn("dwd_modify_time", to_timestamp(lit(current_time)))
      .withColumn("etl_date",date_format(col("create_time"),"yyyyMMdd"))
      .write.format("hudi").mode("append")
      .options(getQuickstartWriteConfigs)
      .option(RECORDKEY_FIELD.key(), "id")
      .option(PRECOMBINE_FIELD.key(), "dwd_modify_time")
      .option(PARTITIONPATH_FIELD.key(), "etl_date")
      .option("hoodie.table.name", "fact_order_detail")
      .save(dwd_path)



    spark.close()

  }

}
